<template>
  <div class="categories-container page-view">
    <div class="categories-header header-section">
      <h1 class="page-title">
        <i class="bi bi-tags me-2"></i>
        分类管理
      </h1>
      <p class="page-subtitle">使用 Element Plus 管理商品分类</p>
    </div>

    <div class="categories-content">
      <!-- 操作与筛选区 -->
      <div class="header-section">
        <div class="search-section">
          <el-input v-model="searchQuery" placeholder="搜索分类名称..." clearable class="w-300 mr-16">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select v-model="selectedStatus" placeholder="全部状态" clearable class="w-150 mr-16">
            <el-option label="全部状态" value="" />
            <el-option label="启用" value="enabled" />
            <el-option label="停用" value="disabled" />
          </el-select>
        </div>

        <div class="action-section">
          <el-button type="primary" @click="openCreate">新增分类</el-button>
        </div>
      </div>

      <!-- 分类列表 -->
      <el-card class="table-card">
        <el-table :data="displayedCategories" stripe style="width: 100%" empty-text="暂无分类">
          <el-table-column label="分类名称" min-width="180">
            <template #default="{ row }">
              <el-text type="primary" class="fw-bold">{{ row.name }}</el-text>
            </template>
          </el-table-column>

          <el-table-column label="描述" min-width="220">
            <template #default="{ row }">
              <div class="desc-text">{{ row.description || "—" }}</div>
            </template>
          </el-table-column>

          <el-table-column label="状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 'enabled' ? 'success' : 'info'" size="small">
                {{ row.status === "enabled" ? "启用" : "停用" }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="创建时间" width="180" align="center">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="260" align="center" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="editCategory(row)">编辑</el-button>
              <el-button
                size="small"
                :type="row.status === 'enabled' ? 'warning' : 'success'"
                @click="toggleStatus(row.id)"
              >
                {{ row.status === "enabled" ? "停用" : "启用" }}
              </el-button>
              <el-button size="small" type="danger" @click="deleteCategory(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑弹窗（示意，未接入后端） -->
    <el-dialog v-model="dialog.visible" :title="dialog.mode === 'create' ? '新增分类' : '编辑分类'">
      <div class="dialog-body">
        <el-form label-width="90px">
          <el-form-item label="名称">
            <el-input v-model="dialog.form.name" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="dialog.form.description" type="textarea" placeholder="请输入描述" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="dialog.form.status" placeholder="请选择状态" class="w-150">
              <el-option label="启用" value="enabled" />
              <el-option label="停用" value="disabled" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="saveDialog">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { Search } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";

defineOptions({
  name: "CategoriesView",
});

// 搜索与筛选
const searchQuery = ref("");
const selectedStatus = ref("");

// 模拟分类数据
type Category = {
  id: number;
  name: string;
  description?: string;
  status: "enabled" | "disabled";
  createdAt: string;
};

const categories = ref<Category[]>([
  { id: 1, name: "手机数码", description: "手机与配件", status: "enabled", createdAt: "2024-01-10T08:20:00Z" },
  {
    id: 2,
    name: "电脑办公",
    description: "电脑、外设与办公用品",
    status: "enabled",
    createdAt: "2024-01-11T10:12:00Z",
  },
  { id: 3, name: "服饰鞋包", description: "服装鞋帽与箱包", status: "disabled", createdAt: "2024-01-12T12:45:00Z" },
  { id: 4, name: "家居家装", description: "家居与装修材料", status: "enabled", createdAt: "2024-01-13T09:00:00Z" },
]);

// 过滤结果
const filteredCategories = computed(() => {
  return categories.value.filter((c) => {
    const matchesSearch = c.name.toLowerCase().includes(searchQuery.value.toLowerCase());
    const matchesStatus = !selectedStatus.value || c.status === selectedStatus.value;
    return matchesSearch && matchesStatus;
  });
});

// 分页
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});

// 当前页数据
const displayedCategories = computed(() => {
  const start = (pagination.value.page - 1) * pagination.value.pageSize;
  return filteredCategories.value.slice(start, start + pagination.value.pageSize);
});

// 监听过滤结果更新总数并重置页码
watch(filteredCategories, (list) => {
  pagination.value.total = list.length;
  pagination.value.page = 1;
});

// 分页事件
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.page = 1;
};

const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
};

// 工具方法
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString("zh-CN");
};

// 操作
const openCreate = () => {
  dialog.value.mode = "create";
  dialog.value.form = { name: "", description: "", status: "enabled" };
  dialog.value.visible = true;
};

const editCategory = (row: Category) => {
  dialog.value.mode = "edit";
  dialog.value.form = { name: row.name, description: row.description || "", status: row.status };
  dialog.value.editingId = row.id;
  dialog.value.visible = true;
};

const toggleStatus = (id: number) => {
  const item = categories.value.find((c) => c.id === id);
  if (item) {
    item.status = item.status === "enabled" ? "disabled" : "enabled";
  }
};

const deleteCategory = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定要删除这个分类吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    categories.value = categories.value.filter((c) => c.id !== id);
    ElMessage.success("已删除分类");
  } catch {
    // 用户取消，不做处理
  }
};

// 弹窗
const dialog = ref<{
  visible: boolean;
  mode: "create" | "edit";
  editingId?: number;
  form: { name: string; description: string; status: "enabled" | "disabled" };
}>({
  visible: false,
  mode: "create",
  form: { name: "", description: "", status: "enabled" },
});

const saveDialog = () => {
  if (!dialog.value.form.name.trim()) {
    alert("分类名称不能为空");
    return;
  }
  if (dialog.value.mode === "create") {
    const nextId = Math.max(0, ...categories.value.map((c) => c.id)) + 1;
    categories.value.push({
      id: nextId,
      name: dialog.value.form.name.trim(),
      description: dialog.value.form.description.trim(),
      status: dialog.value.form.status,
      createdAt: new Date().toISOString(),
    });
  } else if (dialog.value.mode === "edit" && dialog.value.editingId != null) {
    const idx = categories.value.findIndex((c) => c.id === dialog.value.editingId);
    if (idx >= 0) {
      categories.value[idx] = {
        ...categories.value[idx],
        name: dialog.value.form.name.trim(),
        description: dialog.value.form.description.trim(),
        status: dialog.value.form.status,
      };
    }
  }
  dialog.value.visible = false;
};
</script>

<style scoped>
.categories-container {
  padding: 2rem;
  background-color: #f8f9fc;
  min-height: 100vh;
}

.categories-header {
  margin-bottom: 2rem;
}

.page-title {
  color: #5a5c69;
  font-size: 1.75rem;
  font-weight: 400;
  margin-bottom: 0.5rem;
}

.page-subtitle {
  color: #858796;
  margin-bottom: 0;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  gap: 1rem;
  flex-wrap: wrap;
}

.search-section {
  display: flex;
  gap: 0.75rem;
  align-items: center;
}

.action-section {
  display: flex;
  align-items: center;
}

.table-card {
  border: none;
  border-radius: 0.35rem;
}

.desc-text {
  color: #5a5c69;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  padding: 1rem 0 0;
}

/* 简易宽度工具类（与现有风格一致） */
.w-300 {
  width: 300px;
}
.w-150 {
  width: 150px;
}
.mr-16 {
  margin-right: 16px;
}
.fw-bold {
  font-weight: 600;
}
</style>
